import {mapBase} from "../base/common/Constants";
import {pushBuildName} from "./MapLogic";
import AStar from "../Common/AStar";

const {ccclass, property} = cc._decorator;

@ccclass
export default class TestLogic extends cc.Component {

    @property(cc.Node)
    grid: cc.Node = null;

    @property(cc.Node)
    targetNode: cc.Node = null;

    as: AStar;


    // 地图数据
    roadData: mapBase[] = [];

    protected onLoad() {
        this.as = new AStar();
        this.initMap();
    }


    /**
     * 初始化地图
     */
    initMap() {
        let that = this;
        cc.resources.load("level/level12", function (t, i) {
            // console.log(i)
            // console.log('jiazia1')
            // @ts-ignore
            that.loadMap(i.json);
            // console.log('jiazia2')

            // that.data = i.toString();
        });
    }

    /**
     * 加载地图
     * @param data
     */
    loadMap(data) {
        console.log(data.pos)
        console.log(data.data)
        this.roadData = data.data;
        this.as.initMap(this.roadData);
        this.targetNode.setPosition(9999, 9999);
        let number = this.roadData.findIndex(value => value.spawn_point == 1);
        //  玩家坐标赋值
        this.grid.setPosition((this.roadData[number].x - 9) * 50, (5 - this.roadData[number].y) * 50);
        //  储存当前点位
        this.curPos = [this.roadData[number].x, this.roadData[number].y];


    }


    // tween
    moveT;
    // 移动路径
    movePath: number[][] = [];
    // 当前坐标
    curPos: number[] = [];
    // 每格移动时间
    runTime: number = 0.5;



    /**
     * A星寻路
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @constructor
     */
    AsFindPath(startX: number, startY: number, endX: number, endY: number) {
        let as = new AStar();
        return as.findPathByMap(this.roadData, startX, startY, endX, endY);
    }

    /**
     * 追
     */
    trace() {
        let number = Math.floor(Math.random() * pushBuildName.length);
        console.log(number)
        let targetData = this.roadData.find(value => value.pushBuild == number);
        console.log(targetData);
        this.targetNode.setPosition((targetData.x - 9) * 50, (5 - targetData.y) * 50);

        this.movePath = this.AsFindPath(this.curPos[0], this.curPos[1], targetData.x, targetData.y);
        console.log(this.movePath);
        // console.log(p);
        this.move();
    }

    move() {
        if (this.movePath != undefined && this.movePath.length > 1) {
            this.movePath.splice(0, 1);

            this.moveT = cc.tween(this.grid)
                .to(this.runTime, {position: new cc.Vec3((this.movePath[0][0] - 9) * 50, (5 - this.movePath[0][1]) * 50)})
                .call(() => {
                    this.curPos = this.movePath[0];
                    this.move();

                })
                .start()

        } else {
            console.log('到达终点')
        }
    }


}
